package com.vietthanh85.android;

import java.io.BufferedReader;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Search extends Activity {
	/** Called when the activity is first created. */
	
	public final static int SIMPLE_NOTFICATION_ID = 1;
	private NotificationManager mNotificationManager;	
	private Notification notifyDetails;
	
	public static final int EDIT = Menu.FIRST + 1;
	public static final int DELETE = Menu.FIRST + 2;
	public static final int FORGOT = Menu.FIRST + 3;
	int position;

	int id;
	int lineNum = 0;
	String line;
	String[] result;
	int i = 0;
	int fromPending = -1;
	BufferedReader bufferReader;
	File sdCard;
	File newWordsFile;

	ListView wordsList;
	ListAdapter listAdapter;
	
	ArrayList<HashMap<String, String>> list2LineItems = new ArrayList<HashMap<String, String>>();
	ArrayList<HashMap<String, String>> list2LineSearchedItems;
	
	public static Handler handler;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		handler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					finish();
					break;
				case 1:
					search("");
					break;
				}
			}
		};
		Bundle extras = getIntent().getExtras();
		if (extras != null) {			
			fromPending = extras.getInt("fromPending");
			if (fromPending == 0) {
				handler.sendEmptyMessage(0);
				fromPending = -1;
			}
		} else {
			Common.init();
		}
		showNotification();
		final EditText searchET = (EditText) findViewById(R.id.searchET);
		searchET.addTextChangedListener(new TextWatcher() {
			String keyword;

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				keyword = searchET.getText().toString();
				search(keyword);
			}
		});
		Iterator<Line> itr = Common.lineVector.iterator();
		if (!Common.reversed) {
			while (itr.hasNext()) {
				Line lineIns = itr.next();
				HashMap<String, String> item = new HashMap<String, String>();
				item.put("word", lineIns.id + ". " + lineIns.word);
				item.put("info", lineIns.client + " - " + lineIns.time);
				list2LineItems.add(item);
			}
		} else {
			while (itr.hasNext()) {
				Line lineIns = itr.next();
				HashMap<String, String> item = new HashMap<String, String>();
				item.put("word", lineIns.id + ". " + lineIns.meaning);
				item.put("info", lineIns.client + " - " + lineIns.time);
				list2LineItems.add(item);
			}
		}

		wordsList = (ListView) findViewById(R.id.wordLV);
		list2LineSearchedItems = list2LineItems;
		listAdapter = new SimpleAdapter(this, list2LineItems,
				R.layout.twolinelist, new String[] { "word",
						"info" }, new int[] { R.id.info,
						R.id.word });
		wordsList.setAdapter(listAdapter);
		wordsList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Intent intent = new Intent(Search.this, RandomWord.class);
				intent.putExtra("id",
						list2LineItems.indexOf(list2LineSearchedItems.get((int) id)));
				intent.putExtra("lineNum", Common.lineVector.size());
				startActivity(intent);				
			}
		});
		
		registerForContextMenu(wordsList);
		listItemClicked();
		
	}
	
	public void search(String keyword) {
		list2LineSearchedItems = new ArrayList<HashMap<String, String>>();
		Iterator<Line> itr = Common.lineVector.iterator();
		if (!Common.reversed) {
			while (itr.hasNext()) {
				Line lineIns = itr.next();						
				if (lineIns.word.contains(keyword.toLowerCase())) {
					HashMap<String, String> item = new HashMap<String, String>();
					item.put("word", lineIns.id + ". " + lineIns.word);
					item.put("info", lineIns.client + " - " + lineIns.time);
					list2LineSearchedItems.add(item);
				}						
			}
		} else {
			while (itr.hasNext()) {
				Line lineIns = itr.next();						
				if (lineIns.meaning.contains(keyword.toLowerCase())) {
					HashMap<String, String> item = new HashMap<String, String>();
					item.put("word", lineIns.id + ". " + lineIns.meaning);
					item.put("info", lineIns.client + " - " + lineIns.time);
					list2LineSearchedItems.add(item);
				}						
			}
		}
		listAdapter = new SimpleAdapter(Search.this,
				list2LineSearchedItems, R.layout.twolinelist,
				new String[] { "word", "info" }, new int[] {
						R.id.info, R.id.word });
		wordsList.setAdapter(listAdapter);
	}
		
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		populateMenu(menu);
		menu.setHeaderTitle("Options");
	}

	private void populateMenu(ContextMenu menu) {		
		if (Common.weekSelected.equals("ForgotList")) {
			menu.add(Menu.NONE, DELETE, Menu.NONE, "Delete");			
		} else if (Common.weekSelected.equals("CurrentWeek")) {
			menu.add(Menu.NONE, EDIT, Menu.NONE, "Edit");
			menu.add(Menu.NONE, DELETE, Menu.NONE, "Delete");
			menu.add(Menu.NONE, FORGOT, Menu.NONE, "I forgot");			
		} else if (Common.weekSelected.equals("AllWeeks")) {
			menu.add(Menu.NONE, FORGOT, Menu.NONE, "I forgot");
		} else {
			menu.add(Menu.NONE, EDIT, Menu.NONE, "Edit");
			menu.add(Menu.NONE, FORGOT, Menu.NONE, "I forgot");			
		}
	}

	private void listItemClicked() {
		wordsList.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				position = arg2;
				return false;
			}
		});
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		return (applyMenuChoice(item) || super.onContextItemSelected(item));
	}

	private boolean applyMenuChoice(MenuItem item) {
		Iterator<Line> itr;
		Line lineIns;
		HashMap<String, String> map = list2LineSearchedItems.get(position);
		String word = map.get("word");
		String idStr = word.substring(0, word.indexOf("."));			
		int id = Integer.parseInt(idStr);		
		switch (item.getItemId()) {
		case DELETE:
			if (Common.weekSelected.equals("ForgotList")) {
				Common.removeIDFromVector(Common.forgotLineVector, id);
				Common.forgotListChanged = true;
			} else {
				Common.removeIDFromVector(Common.lineVector, id);				
				Common.changed = true;
			}
			list2LineSearchedItems.remove(position);
			wordsList.setAdapter(listAdapter);
			Common.forgotListChanged = true;
			Toast.makeText(getApplicationContext(), "Deleted Successfully!",
					Toast.LENGTH_LONG).show();			
			break;
		case EDIT:
			String type = "";
			String meaning = "";			
			itr = Common.lineVector.iterator();			
			while (itr.hasNext()) {
				lineIns = itr.next();
				if (lineIns.id == id) {					
					type = lineIns.type;
					meaning = lineIns.meaning;
					int typeOrder = 0;
					if (type.equals("(n)")) {
						typeOrder = 0;
					} else if (type.equals("(v)")) {
						typeOrder = 1;
					} else if (type.equals("(adj)")) {
						typeOrder = 2;
					} else if (type.equals("(adv)")) {
						typeOrder = 3;
					} else if (type.equals("(phr)")) {
						typeOrder = 4;
					}  else if (type.equals("(prep)")) {
						typeOrder = 5;
					}  else if (type.equals("<later>")) {
						typeOrder = 6;
					}
					Intent intent = new Intent(Search.this, AddWords.class);
					intent.putExtra("fromRandom", 0);
					intent.putExtra("word", lineIns.word);
					intent.putExtra("typeOrder", typeOrder);
					intent.putExtra("meaning", meaning);
					startActivity(intent);
					break;
				}
			}
			break;
		case FORGOT:
			itr = Common.lineVector.iterator();			
			while (itr.hasNext()) {
				lineIns = itr.next();
				if (lineIns.id == id) {
					String curentDateandTime = Common.sdf.format(new Date());
					Line newLineIns = new Line();
					newLineIns.word = lineIns.word;
					newLineIns.type = lineIns.type;
					newLineIns.meaning = lineIns.meaning;
					newLineIns.client = Common.client;
					newLineIns.time = curentDateandTime;
					int loc = Common.word2Loc(Common.forgotLineVector, newLineIns.word);
					if (loc == -1) {
						newLineIns.id = Common.forgotLineVector.size() + 1;
						Common.forgotLineVector.add(newLineIns);
					} else {
						newLineIns.id = loc + 1;
						Common.forgotLineVector.remove(loc);
						Common.forgotLineVector.insertElementAt(newLineIns, loc);
					}
					Toast.makeText(this, "Added to ForgotList!", Toast.LENGTH_LONG).show();
					Common.forgotListChanged = true;	
					break;
				}
			}
			break;
		}
		return false;
	}
	
	public void showNotification(){
		Context context = getApplicationContext();
		CharSequence contentTitle = "VocabBuilder";
		CharSequence contentText = Common.weekSelected + " is selected";
		Intent notifyIntent = new Intent(this, Search.class);
		notifyIntent.putExtra("fromPending", 0);
		PendingIntent intent =	PendingIntent.getActivity(Search.this, 0, notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);		
		int icon = R.drawable.ic_launcher;
		long when = System.currentTimeMillis();
		notifyDetails = new Notification(icon, contentText, when);
		notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
		String ns = Context.NOTIFICATION_SERVICE;
		mNotificationManager = (NotificationManager) getSystemService(ns);
		mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
	} 
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu, menu);
		for (int i = 0; i < Common.dirArray.length; i++) {
			menu.add(Menu.NONE, Menu.FIRST + i + 1, 0, Common.dirArray[i].substring(0, Common.dirArray[i].indexOf(".")));			
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.Reverse) {
			finish();
			Common.reversed = !Common.reversed;			
			Intent intent = new Intent(Search.this, Search.class);
			intent.putExtra("fromPending", -1);
			startActivity(intent);
		} else if (item.getItemId() == R.id.Random) {
			Intent intent = new Intent(Search.this, RandomWord.class);			
			startActivity(intent);
		} else if (item.getItemId() == R.id.Add) {
			Intent intent;
			if (Common.allSelected) {
				Common.currentFolder = Common.currentWeekFolder;
				Common.currentFileName =  Common.currentWeekFileName;
				Common.lineVector = Common.getDataFromFile(Common.currentFolder, Common.currentFileName);
				finish();
				intent = new Intent(Search.this, Search.class);
				intent.putExtra("fromPending", -1);
				startActivity(intent);
			}
			intent = new Intent(Search.this, AddWords.class);			
			startActivity(intent);
		} else if (item.getItemId() == R.id.Forgot) {
			Common.allSelected = true;
			Common.weekSelected = "ForgotList";
			if (Common.changed) {
				Common.commitToFile(Common.currentFolder, Common.currentFileName);
				Common.changed = false;
			}
			Common.lineVector = Common.forgotLineVector;
			finish();
			Intent intent = new Intent(Search.this, Search.class);
			intent.putExtra("fromPending", -1);
			startActivity(intent);
		} else if (item.getItemId() == R.id.currentWeek) {
			Common.allSelected = false;
			Common.weekSelected = "CurrentWeek";
			if (Common.changed) {
				Common.commitToFile(Common.currentFolder, Common.currentFileName);
				Common.changed = false;
			}
			Common.currentFolder = Common.currentWeekFolder;
			Common.currentFileName =  Common.currentWeekFileName;
			Common.lineVector = Common.getDataFromFile(Common.currentFolder, Common.currentFileName);
			finish();
			Intent intent = new Intent(Search.this, Search.class);
			intent.putExtra("fromPending", -1);
			startActivity(intent);
		} else if (item.getItemId() == R.id.allWeeks) {
			Common.allSelected  = true;
			Common.weekSelected = "AllWeeks";
			if (Common.changed) {
				Common.commitToFile(Common.currentFolder, Common.currentFileName);
				Common.changed = false;
			}
			if (!Common.allFileCreated) {
				Common.makeAllVector();
				Common.allFileCreated = true;
			}
			finish();						
			Intent intent = new Intent(Search.this, Search.class);
			intent.putExtra("fromPending", -1);
			startActivity(intent);			
		} else {
			Common.allSelected = false;			
			for (int i = 0; i < Common.dirArray.length; i++) {
				if (item.getItemId() == (Menu.FIRST + i + 1)) {
					if (Common.changed) {
						Common.commitToFile(Common.currentFolder, Common.currentFileName);
						Common.changed = false;
					}
					Common.currentFolder = Common.currentWeekFolder + "/Outputs";
					Common.currentFileName =  Common.dirArray[i];
					Common.lineVector = Common.getDataFromFile(Common.currentFolder, Common.currentFileName);
					finish();
					Common.weekSelected = Common.dirArray[i].substring(0, Common.dirArray[i].indexOf("."));				
				}
			}
			Intent intent = new Intent(Search.this, Search.class);
			intent.putExtra("fromPending", -1);
			startActivity(intent);
		}		
		return true;
	}
	
	@Override
	protected void onPause() {
	    super.onPause();
	    if (isFinishing()) {
	    	mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
	    }
	}
	
	public void finish() {
		if (Common.changed) {
			Common.commitToFile(Common.currentFolder, Common.currentFileName);
			Common.changed = false;
		}
		if (Common.forgotListChanged) {
			Common.commitToFile(Common.currentWeekFolder + "/Forgot", Common.client + ".txt");
			Common.forgotListChanged = false;
		}
		super.finish();
	}
}
